package org.sang.utils;

import java.security.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class KeyPairGenUtil {
    // 秘钥大小
    public static int KEY_LENGTH = 1024;
    // 算法类型
    public static String ALGORITHM_TYPE = "RSA";

    public static Map<String, String> genkeyPair() throws NoSuchAlgorithmException {
        // 存储公钥和私钥
        Map<String, String> keyPairMap = new HashMap<>();
        // 为 RSA 算法创建keyPairGenerator 对象
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM_TYPE);
        // 创建可信任的随机数源
        SecureRandom secureRandom = new SecureRandom();
        // 使用随机数据源初始化keyPairGenerator 对象
        keyPairGenerator.initialize(KEY_LENGTH, secureRandom);
        // 生成密钥对
        KeyPair keypair = keyPairGenerator.generateKeyPair();
        // 获取公钥
        PublicKey publicKey = keypair.getPublic();
        // 获取私钥
        PrivateKey privateKey = keypair.getPrivate();
        // 使用 Base64 将公钥和私钥转化为字符串
        String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        keyPairMap.put("publicKey", publicKeyStr);
        keyPairMap.put("privateKey", privateKeyStr);
        return keyPairMap;
    }

}
